<template>
    <div class="app-container">
      <!-- 操作栏 -->
      <div class="mb-4">
        <el-button type="primary" @click="handleCreate">新增配置</el-button>
      </div>
  
      <!-- 表格 -->
      <el-table :data="tableData" border stripe>
        <el-table-column prop="appId" label="应用ID" />
        <el-table-column prop="gatewayUrl" label="网关地址" />
        <el-table-column label="类型">
          <template #default="{ row }">
            {{ row.payType === 0 ? '沙箱环境' : '生产环境' }}
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="0"
              :inactive-value="1"
              @change="switchStatus(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <div class="mt-4">
        <el-pagination
          v-model:current-page="pagination.pageNo"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          @current-change="fetchData"
          @size-change="fetchData"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
  
      <!-- 抽屉组件 -->
      <AlipayDrawer
        v-model:visible="drawerVisible"
        :form-data="currentForm"
        :is-edit="isEdit"
        @save="handleSave"
      />
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import AlipayDrawer from './AlipayDrawer.vue'
  import {
    getAlipayListApi,
    addOrUpdateAlipayApi,
    deleteAlipayApi,
    switchStatusApi
  } from '@/api/alipay'
  import type { AlipayItem } from '@/types/alipay'
  
  const tableData = ref<AlipayItem[]>([])
  const drawerVisible = ref(false)
  const isEdit = ref(false)
  const currentForm = ref<AlipayItem>(initForm())
  
  const pagination = reactive({
    pageNo: 1,
    pageSize: 10,
    total: 0
  })
  
  function initForm(): AlipayItem {
    return {
      appId: '',
      privateKey: '',
      aliPublicKey: '',
      notifyUrl: '',
      returnUrl: '',
      payType: 0,
      gatewayUrl: '',
      status: 0
    }
  }
  
  // 获取数据
  const fetchData = async () => {
    const res = await getAlipayListApi({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize
    })
    tableData.value = res.data.records
    pagination.total = res.data.total
  }
  

  // 切换状态
const switchStatus = async (row: AlipayItem) => {
  const originalStatus = row.status
  const newStatus = originalStatus === 0 ? 1 : 0
  try {
     // 立即更新UI状态
     row.status = newStatus
     const {data,msg} =  await switchStatusApi(row.id!)
     console.log(data,msg)
     if (data) {
      ElMessage.success(msg)
      await fetchData() // 强制刷新数据
    } else {
      throw new Error(msg)
    }
  } catch (error: any) {
    // 回滚UI状态
    row.status = originalStatus
    
    // 显示错误信息
    const errorMsg = error.response?.data?.message 
      || error.message 
      || '状态更新失败'
    ElMessage.error(errorMsg)
    
    // 重新获取最新数据
    await fetchData()
  }
}
  
  // 删除
  const handleDelete = (id: number) => {
    ElMessageBox.confirm('确认删除该配置？', '提示', {
      type: 'warning'
    }).then(async () => {
      await deleteAlipayApi(id)
      ElMessage.success('删除成功')
      fetchData()
    })
  }
  
  // 新增
  const handleCreate = () => {
    isEdit.value = false
    currentForm.value = initForm()
    drawerVisible.value = true
  }
  
  // 编辑
  const handleEdit = (row: AlipayItem) => {
    isEdit.value = true
    currentForm.value = { ...row }
    drawerVisible.value = true
  }
  
  // 保存数据
  const handleSave = async (form: AlipayItem) => {
    try {
      await addOrUpdateAlipayApi(form,isEdit.value)

      ElMessage.success('保存成功')
      fetchData()
    } catch (error) {
      console.error('保存失败:', error)
    }
  }
  
  onMounted(() => {
    fetchData()
  })
  </script>
  
  <style scoped lang="scss">
  .app-container {
    padding: 20px;
  }
  </style>